package sddz.foodmanage.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.MyUtils;
import sddz.foodmanage.utils.SpfUtils;

public class AddSelfBuyActivity extends BaseActivity {

    @BindView(R.id.title_text)
    TextView titleText;

    protected ProgressDialog baseDialog;

    private ListView lvAddData;
    private ImageView ivAdd;
    private Button tvSubmit;
    private ImageView ivBack;

    private ArrayList<SelfBuyBean> list_selfBuyBeans = new ArrayList<SelfBuyBean>();
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_self_buy);

        initView();
        initData();
    }

    //初始化数据
    private void initData() {
/*
        //填点假数据
        for(int i=0;i<10;i++){
            SelfBuyBean sbb = new SelfBuyBean("name","kg","33元/kg",10,"300元");
            list_selfBuyBeans.add(sbb);
        }
*/
        adapter = new MyAdapter(this);
        lvAddData.setAdapter(adapter);
    }

    //初始化View
    private void initView() {
        //初始化等待框
        baseDialog = new ProgressDialog(mActivity);
        baseDialog.setMessage("请稍等...");

        lvAddData = (ListView) findViewById(R.id.lv_add_data);
        ivAdd = (ImageView) findViewById(R.id.iv_add);
        tvSubmit = (Button) findViewById(R.id.bt_submit);
        ivBack = (ImageView) findViewById(R.id.iv_back);;

        //添加商品
        ivAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /* @setView 装入自定义View ==> R.layout.dialog_customize
                 * 由于dialog_customize.xml只放置了一个EditView，因此和图8一样
                 * dialog_customize.xml可自定义更复杂的View
                 */
                AlertDialog.Builder customizeDialog =
                        new AlertDialog.Builder(AddSelfBuyActivity.this);
                final View dialogView = LayoutInflater.from(AddSelfBuyActivity.this)
                        .inflate(R.layout.dialog_selfbuy_add,null);
                customizeDialog.setTitle("创建自采商品");
                customizeDialog.setView(dialogView);
                customizeDialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
                customizeDialog.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // 获取EditView中的输入内容
                                EditText et_name = (EditText) dialogView.findViewById(R.id.et_name);
                                EditText et_unit = (EditText) dialogView.findViewById(R.id.et_unit);
                                EditText et_price = (EditText) dialogView.findViewById(R.id.et_price);
                                EditText et_amount = (EditText) dialogView.findViewById(R.id.et_amount);
                                String s_name = et_name.getText().toString();
                                String s_unit = et_unit.getText().toString();
                                String s_price = et_price.getText().toString();
                                String s_amount = et_amount.getText().toString();
                                if(s_name.isEmpty()||s_unit.isEmpty()||s_price.isEmpty()||s_amount.isEmpty()){
                                    Toast.makeText(AddSelfBuyActivity.this,"输入的信息不能为空", Toast.LENGTH_SHORT).show();
                                }else{
                                    if((!MyUtils.isNumber(s_price))||(!MyUtils.isNumber(s_amount))) {
                                        Toast.makeText(AddSelfBuyActivity.this,"输入的数据格式不对", Toast.LENGTH_SHORT).show();
                                    }else{
                                        float f_total_price = Float.valueOf(s_price)*Float.valueOf(s_amount);
                                        SelfBuyBean sbb =
                                                new SelfBuyBean(s_name,s_unit,s_price,Float.valueOf(s_amount),String.valueOf(f_total_price));
                                        list_selfBuyBeans.add(sbb);
                                        adapter.notifyDataSetChanged();
                                    }

                                }
                            }
                        });
                customizeDialog.show();
            }
        });

        //提交
        tvSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SubmitSelfBuy();
            }
        });

        //回退
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeActivity("回退");
            }
        });

    }

    //提交订单
    private void SubmitSelfBuy() {
        if(0>=list_selfBuyBeans.size()){
            Toast.makeText(this,"请添加商品后重试",Toast.LENGTH_SHORT).show();
            return;
        }
        SelfBuyOrderBean orderBean = new SelfBuyOrderBean();
        //初始化时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        orderBean.setBuy_time(dateFormat.format(date));//获取当前时间
        List<SelfBuyBean> selfbuylist = new ArrayList<>();
        for (int q = 0; q < list_selfBuyBeans.size(); q++) {
            SelfBuyBean databean = new SelfBuyBean();
            databean.setName(list_selfBuyBeans.get(q).getName());
            databean.setUnit(list_selfBuyBeans.get(q).getUnit());
            databean.setPrice(list_selfBuyBeans.get(q).getPrice());
            databean.setAmount(list_selfBuyBeans.get(q).getAmount());
            selfbuylist.add(databean);
        }
        orderBean.setData(selfbuylist);
        Log.e("orderBean", JSON.toJSONString(orderBean));
        baseDialog.show();

        HttpUtils.getInstance().POST(mActivity, API.postselfbuy, JSON.toJSONString(orderBean), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                baseDialog.dismiss();
                Log.e("自采提交结果", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (!jsonObject.optString("message").equals("")) {
                            //show(jsonObject.optString("message"));
                        }
                        if (code == 200) {
                            show("提交成功");
                            closeActivity("提交成功");
                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            SubmitSelfBuy();
                        } else if (code == 401) {
                            show(jsonObject.optString("message"));
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });


    }


    /**
     * 自采订单的数据
     */
    public static class SelfBuyOrderBean{
        //买的每个商品的详细信息
        private List<SelfBuyBean> data;
        //购买时间
        private String buy_time;

        public void setBuy_time(String buy_time) {
            this.buy_time = buy_time;
        }

        public String getBuy_time() {
            return buy_time;
        }

        public void setData(List<SelfBuyBean> data) {
            this.data = data;
        }
        public List<SelfBuyBean> getData() {
            return data;
        }

    }
    ////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * 自采商品的数据
     */
    public class SelfBuyBean{

        private String name;                //名称
        private String unit;                //单位
        private String price;               //单价
        private float amount;               //数量
        private String total_price;         //总价钱

        SelfBuyBean(){
        }
        SelfBuyBean(String n,String u,String p,float a,String t){
            this.name = n;
            this.unit = u;
            this.price = p;
            this.amount = a;
            this.total_price = t;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        public void setUnit(String unit) {
            this.unit = unit;
        }

        public String getUnit() {
            return unit;
        }

        public void setPrice(String price) {
            this.price = price;
        }

        public String getPrice() {
            return price;
        }

        public void setAmount(float amount) {
            this.amount = amount;
        }

        public float getAmount() {
            return amount;
        }

        public void setTotal_price(String total_price) {
            this.total_price = total_price;
        }

        public String getTotal_price() {
            return total_price;
        }
    }


    /**
     * 自定义的Adapter
     */
    public class MyAdapter extends BaseAdapter {

        private LayoutInflater inflater;

        public MyAdapter(Context context) {
            this.inflater=LayoutInflater.from(context);
        }
        @Override
        public int getCount() {
            return list_selfBuyBeans==null?0:list_selfBuyBeans.size();
        }

        @Override
        public Object getItem(int i) {
            return list_selfBuyBeans.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            final int temp_i = i;
            //加载布局为一个视图

            View my_view=inflater.inflate(R.layout.layout_selfbuy_item,null);
            //在view视图中查找id为image_photo的控件
            TextView tv_name = my_view.findViewById(R.id.tv_name);
            TextView tv_unit = my_view.findViewById(R.id.tv_unit);
            TextView tv_price = my_view.findViewById(R.id.tv_price);
            TextView tv_amout = my_view.findViewById(R.id.tv_amout);
            TextView tv_modify = my_view.findViewById(R.id.tv_modify);
            TextView tv_delete = my_view.findViewById(R.id.tv_delete);

            tv_name.setText(list_selfBuyBeans.get(i).getName());
            tv_unit.setText(list_selfBuyBeans.get(i).getUnit());
            tv_price.setText(list_selfBuyBeans.get(i).getPrice()+"元/"+list_selfBuyBeans.get(i).getUnit());
            tv_amout.setText(Float.toString(list_selfBuyBeans.get(i).getAmount())+list_selfBuyBeans.get(i).getUnit());
            tv_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    list_selfBuyBeans.remove(temp_i);
                    adapter.notifyDataSetChanged();
                }
            });
            tv_modify.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    /* @setView 装入自定义View ==> R.layout.dialog_customize
                     * 由于dialog_customize.xml只放置了一个EditView，因此和图8一样
                     * dialog_customize.xml可自定义更复杂的View
                     */
                    AlertDialog.Builder customizeDialog =
                            new AlertDialog.Builder(AddSelfBuyActivity.this);
                    final View dialogView = LayoutInflater.from(AddSelfBuyActivity.this)
                            .inflate(R.layout.dialog_selfbuy_add,null);
                    customizeDialog.setTitle("编辑自采商品");
                    customizeDialog.setView(dialogView);

                    final EditText et_name = (EditText) dialogView.findViewById(R.id.et_name);
                    final EditText et_unit = (EditText) dialogView.findViewById(R.id.et_unit);
                    final EditText et_price = (EditText) dialogView.findViewById(R.id.et_price);
                    final EditText et_amount = (EditText) dialogView.findViewById(R.id.et_amount);
                    et_name.setText(list_selfBuyBeans.get(temp_i).getName());
                    et_unit.setText(list_selfBuyBeans.get(temp_i).getUnit());
                    et_price.setText(list_selfBuyBeans.get(temp_i).getPrice());
                    et_amount.setText(String.valueOf(list_selfBuyBeans.get(temp_i).getAmount()));

                    customizeDialog.setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // 获取EditView中的输入内容
                                    String s_name = et_name.getText().toString();
                                    String s_unit = et_unit.getText().toString();
                                    String s_price = et_price.getText().toString();
                                    String s_amount = et_amount.getText().toString();
                                    if(s_name.isEmpty()||s_unit.isEmpty()||s_price.isEmpty()||s_amount.isEmpty()){
                                        Toast.makeText(AddSelfBuyActivity.this,"输入的信息不能为空", Toast.LENGTH_SHORT).show();
                                    }else{
                                        if(!MyUtils.isNumber(s_price)||!MyUtils.isNumber(s_amount)) {
                                            Toast.makeText(AddSelfBuyActivity.this,"输入的数据格式不对", Toast.LENGTH_SHORT).show();
                                        }else{
                                            float f_total_price = Float.valueOf(s_price)*Float.valueOf(s_amount);
                                            list_selfBuyBeans.get(temp_i).setName(s_name);
                                            list_selfBuyBeans.get(temp_i).setUnit(s_unit);
                                            list_selfBuyBeans.get(temp_i).setPrice(s_price);
                                            list_selfBuyBeans.get(temp_i).setAmount(Float.valueOf(s_amount));
                                            list_selfBuyBeans.get(temp_i).setTotal_price(String.valueOf(f_total_price));
                                            adapter.notifyDataSetChanged();

                                        }

                                    }
                                }
                            });
                    customizeDialog.show();

                }
            });
            return my_view;
        }
    }

    /**
     * 关闭该activity并返回数据
     * @param s 需要返回的数据
     */
    private void closeActivity(String s){
        //数据是使用Intent返回
        Intent intent = new Intent();
        //把返回数据存入Intent
        intent.putExtra("result",s);
        //设置返回数据
        this.setResult(RESULT_OK, intent);
        //关闭Activity
        this.finish();
    }



}